import React, { useCallback, useEffect, useMemo, useState } from 'react'
import Taro from '@tarojs/taro'
import { Image, Swiper, SwiperItem, Text, View } from '@tarojs/components'
import i18n from '@I18N'
import api from '@API'
import DBConfig from '@CONFIG/DBConfig'
import { LanguageType, ThirdUrlITF } from '@INTERFACES/Common'
import { openPage } from '@UTILS/common'
import { GoodsITF, ShipmentITF } from '@INTERFACES/Goods'
import Navigate from '@NAVIGATION/navigateManager'
import { SHIPMENT_STATUS_ENUM } from '@CONSTANTS/order'
import { Analytic_Type } from '@CONSTANTS/analytic'
import PlanBenefitsCard from '@COMPONENTS/PlanManagement/PlanBenefitsCard'
import { PicTextConsultationITF } from '@INTERFACES/PlanManagement'
import PicTextRightCard from '@COMPONENTS/PlanManagement/PicTextRightCard'
import style from './PlanMyRight.module.scss'

const SEVEN_DAY = 24 * 60 * 60 * 7 * 1000

interface MyRightProps {
  shipmentList: ShipmentITF[]
  orderId: string
  shipmentState: SHIPMENT_STATUS_ENUM
  signedDate: number
  showGoods: boolean
  picTextConsultation: PicTextConsultationITF
  painManagementId: string
}

interface ItemProps {
  language: LanguageType
  onClickGood: (url: ThirdUrlITF) => void
  data: GoodsITF
  quantity: number
}

const PlanMyRight: React.FC<MyRightProps> = ({
  shipmentList = [], orderId, shipmentState, signedDate,
  showGoods, picTextConsultation, painManagementId
}) => {
  const language = 'zh'
  const isNone = useMemo(() => (shipmentState === SHIPMENT_STATUS_ENUM.None), [shipmentState])

  const isInSevenDay = useMemo(() => (!signedDate || (Date.now() - signedDate <= SEVEN_DAY)), [signedDate])
  const goodSKUNames = useMemo(
    () => (Array.isArray(shipmentList) ? shipmentList.map(item => item.GoodsSKU) : []),
    [shipmentList]
  )
  const [data, setData] = useState([])
  const isOne = Array.isArray(data) && data.length === 1
  const onClickGood = (url: ThirdUrlITF) => {
    const { H5Path, WmpPath, wxAppId } = url
    const routeData = {
      h5Path: H5Path,
      wmpPath: WmpPath,
      wxAppId
    }
    openPage('wmpRoute', routeData)
  }

  const fetchData = useCallback(async () => {
    if (!goodSKUNames?.length) return
    try {
      const result = await api.getGoodsBySKUNames({ sn: JSON.stringify(goodSKUNames) })
      const { GoodsList } = result
      setData(GoodsList)
    } catch (e) {
      await Taro.showToast({
        title: e.message || e,
        icon: 'none'
      })
    }
  }, [goodSKUNames])
  useEffect(() => {
    fetchData()
  }, [fetchData])
  const onClickShipment = useCallback(() => {
    if (isNone) return
    Navigate.shipmentList({ orderId })
    Taro.tracker.trackEvent(Analytic_Type.num_see_shipment.eventId)
  }, [isNone, orderId])
  const btnText = isNone ? '待发货' : '查看物流'
  const showGoodsCard = showGoods && data?.length > 0
  const [swiperCurrent, setSwiperCurrent] = useState(0)
  const onSwiperChange = useCallback(e => {
    setSwiperCurrent(e.detail.current)
  }, [])

  if (!showGoodsCard && !picTextConsultation?.Quantity) return null

  return (
    <View className={style.container}>
      <View className={style.containerClass}>
        <View className={style.block} />
        <Text className={style.rightTitle}>{i18n.servicePack.my_rights()}</Text>
      </View>
      {showGoodsCard && (
        <PlanBenefitsCard
          containerClass={style.marTop16}
          onClickBtn={onClickShipment}
          title="商品权益"
          btnText={isInSevenDay ? btnText : ''}
        >
          <Swiper
            className={style.swiperView}
            circular={!isOne}
            onChange={onSwiperChange}
          >
            {
              data.map((item, idx) => (
                <SwiperItem key={`goods_${idx}`} className={isOne ? '' : style.content}>
                  <RenderItem
                    onClickGood={onClickGood}
                    language={language}
                    data={item}
                    quantity={shipmentList[idx].Quantity}
                  />
                </SwiperItem>
              ))
            }
          </Swiper>

          {!isOne && (
          <View className={style.indicatorWrapper}>
            {
              data.map((_item, idx) => (
                <View className={`${style.indicators} ${swiperCurrent === idx ? style.active : ''}`} key={idx} />
              ))
            }
          </View>
          )}
        </PlanBenefitsCard>
      )}
      <PicTextRightCard picTextConsultation={picTextConsultation} painManagementId={painManagementId} />
    </View>
  )
}

const RenderItem: React.FC<ItemProps> = ({
  onClickGood, data, language, quantity
}) => {
  const { Name, Description, PreviewFileName, Url } = data || {}
  const name = Name?.[language] || ''
  const desc = Description?.[language] || ''
  const src = `${DBConfig.staticGoodsUrl}${PreviewFileName}`
  const onClick = () => onClickGood(Url)
  if (!data) return null
  return (
    <View className={style.swiperItem} onClick={onClick}>
      <View className={style.image}>
        <Image src={src} className={style.image} />
      </View>
      <View className={style.goodContent}>
        <View className={style.goodHeader}>
          <Text className={style.goodTitle}>{name}</Text>
          <Text className={style.goodNum}>{`x${quantity}`}</Text>
        </View>
        <Text className={style.goodDesc}>{desc}</Text>
      </View>
    </View>
  )
}

export default PlanMyRight
